package com.golden.procedure.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.golden.procedure.dao.ProductDeliveryDetailMapper;
import com.golden.procedure.dao.WorkDesignOrderMapper;
import com.golden.procedure.dao.WorkPhotoFilmMapper;
import com.golden.procedure.domain.OrderProductDO;
import com.golden.procedure.domain.ProductDeliveryDetailDO;
import com.golden.procedure.domain.ProductDeliveryRecordDO;
import com.golden.procedure.domain.WorkCommentDO;
import com.golden.procedure.domain.WorkOrderDO;
import com.golden.procedure.domain.WorkTaskHistoryDO;
import com.golden.procedure.entity.ProductDeliveryDetail;
import com.golden.procedure.entity.ProductDeliveryDetailExample;
import com.golden.procedure.entity.WorkDesignOrder;
import com.golden.procedure.entity.WorkDesignOrderExample;
import com.golden.procedure.entity.WorkPhotoFilmExample;
import com.golden.procedure.query.WorkOrderQueryDO;
import com.golden.procedure.result.ResultDO;
import com.golden.procedure.result.ResultSupport;
import com.golden.procedure.service.IProductDeliveryService;
import com.golden.procedure.service.IWorkCommentService;
import com.golden.procedure.service.IWorkOrderService;
import com.golden.procedure.service.IWorkPhotoProductService;
import com.golden.procedure.service.IWorkTaskHistoryService;
import com.golden.procedure.util.BeanUtilsExtends;
import com.golden.procedure.util.BonConstant;
import com.golden.procedure.util.TaskDefKey;

/**
 * 产品交货 <b>Description:</b><br>
 * 
 * @author Reading.Reagan</a>
 * @version 1.0
 * @Note <b>ProjectName:</b> procedure <br>
 *       <b>PackageName:</b> com.golden.procedure.service.impl <br>
 *       <b>ClassName:</b> ProductDeliveryService <br>
 *       <b>Date:</b> 2018年10月22日 下午4:14:14
 */
@Service("productDeliveryService")
public class ProductDeliveryService extends BaseService implements IProductDeliveryService {

	@Autowired
	ProductDeliveryDetailMapper productDeliveryDetailMapper;
	@Autowired
	WorkDesignOrderMapper workDesignOrderMapper;
	@Autowired
	WorkPhotoFilmMapper workPhotoFilmMapper;
	@Autowired
	IWorkOrderService workOrderService;
	@Autowired
	IWorkCommentService workCommentService;
	@Autowired
	IWorkTaskHistoryService workTaskHistoryService;
	@Autowired
	IWorkPhotoProductService workPhotoProductService;

	/**
	 * 添加交货记录 <b>Description: 添加交货记录，可批量交货； 所有商品完成交货后，该工单服务状态标记为 已完成</b><br>
	 * 
	 * @param domain
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月20日 下午3:43:42 <br>
	 *       <b>Version:</b> 1.0
	 */
	@Override
	public ResultDO add(ProductDeliveryDetailDO domain) {
		ResultDO result = new ResultSupport();
		// 1.工单参数验证
		if (isNumberInValid(domain.getWorkOrderID())) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("参数错误");
			return result;
		}
		// 2.查询工单
		ResultDO resultDO = workOrderService.get(domain.getWorkOrderID());
		if (!resultDO.isSuccess()) {
			return resultDO;
		}
		WorkOrderDO orderDO = (WorkOrderDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);

		// TODO: 4.查询订单商品列表
		// List<OrderProductDO> productList = getProductList(orderDO.getId(),
		// orderDO.getOrderID(),
		// orderDO.getOrderProductSceenID());
		// 查询订单商品及入册数据、入底数据
		List<OrderProductDO> productList = getProductList(orderDO, domain.getWorkOrderID(),
				domain.getBusinessNo());

		// 4.写入交货记录数据
		for (Integer productID : domain.getOrderProductIDs()) {
			for (OrderProductDO data : productList) {
				if (productID.equals(data.getOrderProductID())) {
					// 交货记录对象
					ProductDeliveryDetail entity = new ProductDeliveryDetail();
					if (!BeanUtilsExtends.copyProperties(entity, domain)) {
						result.setSuccess(false);
						result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
						result.setErrorMsg("数据格式转换错误");
						return result;
					}

					entity.setOrderID(orderDO.getOrderID());
					entity.setOrderProductSceenID(orderDO.getOrderProductSceenID());
					entity.setOrderProductID(productID);
					entity.setOrderProductName(data.getOrderProductName());
					entity.setProductNum(data.getProductNum());
					entity.setDeliveryDate(new Date(Long.parseLong(domain.getDeliveryDateStr())));
					entity.setStatus(BonConstant.STATUS_TRUE); // 状态：交货完成
					entity.setIsDelete(BonConstant.DB_NORMAL);
					entity.setCreatetime(Calendar.getInstance().getTime());

					int ret = productDeliveryDetailMapper.insert(entity);
					if (ret < 1) {
						result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
						result.setErrorMsg("添加失败");
						result.setSuccess(false);
					}
				}
			}
		}

		// 判断是否所有商品都全部交货
		ProductDeliveryDetailExample example = new ProductDeliveryDetailExample();
		ProductDeliveryDetailExample.Criteria criteria = example.createCriteria();
		criteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
		criteria.andStatusEqualTo(BonConstant.STATUS_TRUE);
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);

		int count = productDeliveryDetailMapper.countByExample(example);
		// 交货记录数与制作商品数相等，认为是已经全部交货完成
		if (count == productList.size()) {
			// 更新工单表数据（工单服务完成）
			WorkOrderDO entity = new WorkOrderDO();
			entity.setId(orderDO.getId());
			entity.setTaskDefID(TaskDefKey.PRODUCT_DELIVERY.getKey());
			// 工单服务状态为： 完成（至此工单流程结束）
			entity.setStatus(BonConstant.WORKORDER_STATUS_COMPLETED);
			resultDO = workOrderService.edit(entity);
			if (!resultDO.isSuccess()) {
				// 工单服务状态修改失败
				result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg("工单状态修改失败");
				result.setSuccess(false);
				return result;
			}

			// 写入任务记录表
			WorkTaskHistoryDO taskHistoryDO = new WorkTaskHistoryDO();
			taskHistoryDO.setWorkOrderID(orderDO.getId());
			taskHistoryDO.setProcessInstanceID(orderDO.getProcessInstanceID());
			taskHistoryDO.setTaskDefID(TaskDefKey.PRODUCT_DELIVERY.getKey()); // 交货
			taskHistoryDO.setTaskName(TaskDefKey.PRODUCT_DELIVERY.getName());
			taskHistoryDO.setTaskID(""); // 从acitivti获取
			taskHistoryDO.setSchedulingdate(domain.getDeliveryDate());
			taskHistoryDO.setEndOn(Calendar.getInstance().getTime());
			taskHistoryDO.setStatus(BonConstant.STATUS_TRUE);
			taskHistoryDO.setAuthorID(domain.getAuthorID());
			taskHistoryDO.setAuthor(domain.getAuthor());
			workTaskHistoryService.add(taskHistoryDO);
		}

		// 写入服务记录
		WorkCommentDO commentDO = new WorkCommentDO();
		commentDO.setWorkOrderID(orderDO.getId());
		commentDO.setProcessInstanceID(orderDO.getProcessInstanceID());
		commentDO.setTaskDefID(TaskDefKey.PRODUCT_DELIVERY.getKey()); // 选片
		commentDO.setTaskName(TaskDefKey.PRODUCT_DELIVERY.getName());
		commentDO.setTaskID(""); // 从acitivti获取
		commentDO.setType(BonConstant.COMMENT_TYPE_REMARK); // 0备注；1事件
		commentDO.setRemark(domain.getComment());
		commentDO.setAuthorID(domain.getAuthorID());
		commentDO.setAuthor(domain.getAuthor());
		workCommentService.add(commentDO);

		return result;
	}

	@Override
	public ResultDO query(WorkOrderQueryDO domain) {

		// 查询任务节点为：设计制作/产品交换的工单
		ResultDO resultDO = workOrderService.query(domain);
		if (!resultDO.isSuccess()) {
			return resultDO;
		}
		List<WorkOrderDO> list = (List<WorkOrderDO>) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);

		// 查询设计制作单数据，通过工单id生成map，方便查询
		WorkDesignOrderExample example = new WorkDesignOrderExample();
		WorkDesignOrderExample.Criteria criteria = example.createCriteria();
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);
		example.setOrderByClause(" id desc ");
		List<WorkDesignOrder> designList = workDesignOrderMapper.selectByExample(example);
		Map<Integer, WorkDesignOrder> designMap = new HashMap<Integer, WorkDesignOrder>();
		for (int i = 0; i < designList.size(); i++) {
			WorkDesignOrder data = designList.get(i);
			if (!designMap.containsKey(data.getWorkOrderID())) {
				designMap.put(data.getWorkOrderID(), data);
			}
		}

		List<ProductDeliveryRecordDO> doList = new ArrayList<ProductDeliveryRecordDO>();
		// 填充产品交货列表数据
		for (int i = 0; i < list.size(); i++) {
			WorkOrderDO workOrder = list.get(i);
			ProductDeliveryRecordDO recordDO = new ProductDeliveryRecordDO();
			recordDO.setWorkOrder(workOrder);
			recordDO.setWorkOrderID(workOrder.getId());
			recordDO.setStatus(workOrder.getStatus());

			// 统计发货详情页（有数据：部分发货； 无数据：未发货）
			ProductDeliveryDetailExample detailExample = new ProductDeliveryDetailExample();
			ProductDeliveryDetailExample.Criteria detailCriteria = detailExample.createCriteria();
			detailCriteria.andWorkOrderIDEqualTo(workOrder.getId());
			detailCriteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);
			detailExample.setOrderByClause(" id desc ");
			List<ProductDeliveryDetail> details = productDeliveryDetailMapper.selectByExample(detailExample);
			if (null != details && details.size() > 0) {
				if (workOrder.getStatus() == BonConstant.STATUS_TRUE) {
					// 工单状态为已完成时，标明发货已完成
					recordDO.setStatusName("完成");
					// 最后一条数据的结束时间为交货完成时间
					recordDO.setDeliveryDate(details.get(0).getCreatetime());
					recordDO.setDeliveryDateStr(details.get(0).getCreatetime().getTime() + "");
				} else {
					// 工单状态为进行中时， 标明为 部分发货
					recordDO.setStatusName("部分发货");
				}
			} else {
				// 无发货记录时，为未发货
				recordDO.setStatusName("未发货");
			}

			// 补充制作单数据（计划取件时间、照片数、制作产品数）
			if (designMap.containsKey(workOrder.getId())) {
				WorkDesignOrder designOrder = designMap.get(workOrder.getId());
				recordDO.setPhotoNum(designOrder.getPhotoNum());
				recordDO.setProductNum(designOrder.getProductNum());
				recordDO.setBusinessNo(designOrder.getBusinessNo());
				if (null != designOrder.getDeliveryDate()) {
					recordDO.setPlanDeliveryDate(designOrder.getDeliveryDate());
					recordDO.setPlanDeliveryDateStr(designOrder.getDeliveryDate().getTime() + "");
				}
			}
			doList.add(recordDO);
		}

		resultDO.setModel(ResultDO.FIRST_MODEL_KEY, doList);
		return resultDO;
	}

	@Override
	public ResultDO queryDetail(ProductDeliveryRecordDO domain) {

		ResultDO result = new ResultSupport();
		// 1.参数验证
		if (isNumberInValid(domain.getWorkOrderID())) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("参数错误");
			return result;
		}
		// 2.查询工单
		ResultDO resultDO = workOrderService.get(domain.getWorkOrderID());
		if (!resultDO.isSuccess()) {
			return resultDO;
		}
		WorkOrderDO orderDO = (WorkOrderDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);

		// TODO: 查询本次待制作的订单商品列表
		// List<OrderProductDO> productList = getProductList(orderDO.getId(),
		// orderDO.getOrderID(),
		// orderDO.getOrderProductSceenID());

		// 查询订单商品及入册数据、入底数据
		List<OrderProductDO> productList = getProductList(orderDO, domain.getWorkOrderID(),
				domain.getBusinessNo());

		List<ProductDeliveryDetailDO> doList = new ArrayList<ProductDeliveryDetailDO>();

		if (null != productList && productList.size() > 0) {
			// 查询已交货记录
			ProductDeliveryDetailExample detailExample = new ProductDeliveryDetailExample();
			ProductDeliveryDetailExample.Criteria detailCriteria = detailExample.createCriteria();
			detailCriteria.andWorkOrderIDEqualTo(domain.getWorkOrderID());
			detailCriteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);
			detailExample.setOrderByClause(" id desc ");
			List<ProductDeliveryDetail> details = productDeliveryDetailMapper.selectByExample(detailExample);

			Map<Integer, ProductDeliveryDetail> detailMap = new HashMap<Integer, ProductDeliveryDetail>();
			for (ProductDeliveryDetail data : details) {
				detailMap.put(data.getOrderProductID(), data);
			}
			// 对比已交货记录
			for (OrderProductDO data : productList) {
				ProductDeliveryDetailDO detailDO = new ProductDeliveryDetailDO();
				detailDO.setOrderProductID(data.getOrderProductID());
				detailDO.setOrderProductName(data.getOrderProductName());
				detailDO.setProductNum(data.getProductNum());
				detailDO.setStatusName("未交货");
				// 判断是否已交货
				if (detailMap.containsKey(data.getOrderProductID())) {
					ProductDeliveryDetailDO entity = getProductDeliveryDetailDO(
							detailMap.get(data.getOrderProductID()));
					if (null != entity) {
						detailDO = entity;
						detailDO.setStatusName("OK");
					}
				}
				doList.add(detailDO);
			}
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
		return result;
	}

	public ProductDeliveryDetailDO getProductDeliveryDetailDO(ProductDeliveryDetail obj) {
		if (obj == null)
			return null;
		ProductDeliveryDetailDO dst = new ProductDeliveryDetailDO();
		BeanUtilsExtends.copyProperties(dst, obj);
		dst.setModifitime(obj.getModifitime().getTime() + "");
		dst.setCreatetime(obj.getCreatetime().getTime() + "");
		if (null != obj.getDeliveryDate()) {
			dst.setDeliveryDateStr(obj.getDeliveryDate().getTime() + "");
		}
		if (dst.getStatus() == BonConstant.STATUS_TRUE) {
			dst.setStatusName("OK");
		} else {
			dst.setStatusName("部分交货");
		}
		return dst;
	}

	public List<OrderProductDO> getProductList(WorkOrderDO workOrder, Integer workOrderID, String businessNo) {
		// 查询入底数（包含自备底片）
		List<OrderProductDO> productList = workPhotoProductService.getPickProducts(workOrderID, businessNo);

		// 查询入底数（包含自备底片）
		WorkPhotoFilmExample filmExample = new WorkPhotoFilmExample();
		WorkPhotoFilmExample.Criteria filmCriteria = filmExample.createCriteria();
		filmCriteria.andWorkOrderIDEqualTo(workOrderID);
		filmCriteria.andBusinessNoEqualTo(businessNo);
		filmCriteria.andStatusEqualTo(BonConstant.STATUS_TRUE);
		filmCriteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);

		int rdCount = workPhotoFilmMapper.countByExample(filmExample);
		OrderProductDO rdProductDO = new OrderProductDO();
		rdProductDO.setOrderID(workOrder.getOrderID()); // 订单ID
		rdProductDO.setOrderProductSceenID(workOrder.getOrderProductSceenID()); // 场次ID
		rdProductDO.setBusinessNo(businessNo);
		rdProductDO.setOrderProductID(0); // TODO： 入底商品ID???
		rdProductDO.setOrderProductName("入底照片"); // 入底
		rdProductDO.setPhotoNum(rdCount);
		productList.add(rdProductDO);

		return productList;
	}
}
